﻿using System.Collections.Generic;
using System.Web.Mvc;
using Jw.Models;

namespace Jw.Web
{
    //ActionFilterAttribute是Action过滤类,
    //该属于会在执行一个action之前先执行.而ActionFilterAttribute是 MVC的一个专门处理action过滤的类.基于这个原理 我们做一个权限限制 
    public class MvcMenuFilter : ActionFilterAttribute
    {
        private bool _isEnable = true;

        public MvcMenuFilter()
        {
            _isEnable = true;
        }

        public MvcMenuFilter(bool IsEnable)
        {
            _isEnable = IsEnable;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //二次校验权限(这个处理可能会造成，如果URL传参有冲突-没有找到很好的处理方法前暂时屏蔽
            if (_isEnable)
            {
                var list = new List<string>();
                var route = filterContext.RouteData.Values;
                var url = string.Format("/{0}/{1}/{2}", route["area"], route["controller"], route["action"]);
                //解析第四个参数
                if (route["Id"] != null)
                {
                    url = string.Format("/{0}/{1}/{2}/{3}", route["area"], route["controller"], route["action"], route["Id"]);
                }
                list.Add(url);

                if (url.EndsWith("/Index"))
                {
                    url = url.Substring(0, url.Length - 6);
                    list.Add(url);
                }

                if (url.EndsWith("/Home"))
                {
                    url = url.Substring(0, url.Length - 5);
                    list.Add(url);
                }

                if (!new sys_userService().AuthorizeUserMenu(list))
                    filterContext.Result = new ContentResult() { Content = "你没有访问此功能的权限，请联系管理员！" };
            }

            base.OnActionExecuting(filterContext);
        }
    }
}